package com.zb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.zb.dto.*;
import com.zb.entity.TbAlarmModel;
import com.zb.influx.InfluxRepository;
import com.zb.mapper.TbAlarmMapper;
import com.zb.service.TbAlarmService;
import com.zb.vo.Pager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @ClassName TbAlarmServiceImpl
 * @Description 服务接口实现
 * @Author xm
 * @Date 2024/08/08 10:15
 **/
@Service
public class TbAlarmServiceImpl extends ServiceImpl<TbAlarmMapper, TbAlarmModel> implements TbAlarmService {

    @Autowired
    private InfluxRepository influxRepository;

    @Override
    public Pager<QuotaAllInfo> queryAlarmLog
            (Long page, Long pageSize, String start, String end, String alarmName, String deviceId) {
        StringBuffer whereQl = new StringBuffer(" where alarm = '1' ");
        if (!Strings.isNullOrEmpty(start)) {
            whereQl.append(" and time >= '" + start + "' ");
        }
        if (!Strings.isNullOrEmpty(end)) {
            whereQl.append(" and time <='" + end + "' ");
        }
        if (!Strings.isNullOrEmpty(alarmName)) {
            whereQl.append(" and alarmName=~/" + alarmName + "/ ");
        }
        if (!Strings.isNullOrEmpty(deviceId)) {
            whereQl.append(" and deviceId=~/" + deviceId + "/ ");
        }
        StringBuffer selQl = new StringBuffer(" select * from quota ");
        selQl.append(whereQl.toString());
        selQl.append(" order by desc limit " + pageSize + " offset " + (page - 1) * pageSize);
        System.out.println(selQl.toString());

        StringBuffer countQl = new StringBuffer(" select count(value) from quota ");
        countQl.append(whereQl.toString());
        System.out.println(countQl.toString());
        List<QuotaAllInfo> quotaAll = influxRepository.query(selQl.toString(), QuotaAllInfo.class);
        //日期格式化处理
        for (QuotaAllInfo quotaAllInfo : quotaAll) {
            LocalDateTime dateTime = LocalDateTime.parse(quotaAllInfo.getTime(), DateTimeFormatter.ISO_OFFSET_DATE_TIME);
            String time = dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            quotaAllInfo.setTime(time);
        }

        List<QuotaCount> quotaCount = influxRepository.query(countQl.toString(), QuotaCount.class);
        if (quotaCount == null || quotaCount.size() <= 0) {
            Pager<QuotaAllInfo> pager = new Pager<QuotaAllInfo>(0L, 0L);
            return pager;
        }
        Pager<QuotaAllInfo> pager = new Pager<QuotaAllInfo>(quotaCount.get(0).getCount(), pageSize);
        pager.setPage(page);
        pager.setItems(quotaAll);
        return pager;
    }

    @Override
    public DeviceInfoDTO verifyDeviceInfo(DeviceInfoDTO deviceInfoDTO) {
        //获取设备信息
        DeviceDTO deviceDTO = deviceInfoDTO.getDeviceDTO();
        deviceDTO.setAlarm(false);
        deviceDTO.setAlarmName("正常");
        deviceDTO.setLevel(0);
        deviceDTO.setOnline(true);
        deviceDTO.setStatus(true);
        //遍历指标坚持设备是否报警
        for (QuotaDTO quotaDTO : deviceInfoDTO.getQuotaList()) {
            //根据指标获取报警信息
            TbAlarmModel alarmModel = this.verifyQuota(quotaDTO);
            if (alarmModel != null) { //如果设备报警
                quotaDTO.setAlarm("1");
                quotaDTO.setAlarmName(alarmModel.getName());
                quotaDTO.setLevel(alarmModel.getLevel() + "");
                quotaDTO.setAlarmWebhook(alarmModel.getWebhook());
                quotaDTO.setCycle(alarmModel.getCycle());
                if (alarmModel.getLevel().intValue() > deviceDTO.getLevel().intValue()) {
                    deviceDTO.setLevel(alarmModel.getLevel());
                    deviceDTO.setAlarm(true);
                    deviceDTO.setAlarmName(alarmModel.getName());
                }
            } else {
                quotaDTO.setAlarm("0");
                quotaDTO.setAlarmName("正常");
                quotaDTO.setLevel("0");
                quotaDTO.setAlarmWebhook("");
                quotaDTO.setCycle(0);
            }
        }
        return deviceInfoDTO;
    }


    @Override
    public TbAlarmModel verifyQuota(QuotaDTO quotaDTO) {
        //根据指标编号查询告警信息集合
        LambdaQueryWrapper<TbAlarmModel> qw = new LambdaQueryWrapper<>();
        qw.eq(TbAlarmModel::getQuotaId, quotaDTO.getId());
        List<TbAlarmModel> alarmModelList = this.list(qw);
        TbAlarmModel alarmModel = null;
        for (TbAlarmModel tbAlarmModel : alarmModelList) {
            if ("String".equals(quotaDTO.getValueType())
                    || "Boolean".equals(quotaDTO.getValueType())) {
                if (tbAlarmModel.getOperator().equals("=")
                        && quotaDTO.getStringValue().equals(tbAlarmModel.getThreshold())) {
                    alarmModel = tbAlarmModel;
                    break;
                }
            } else {
                if (tbAlarmModel.getOperator().equals(">")
                        && quotaDTO.getValue() > tbAlarmModel.getThreshold()) {
                    alarmModel = tbAlarmModel;
                    break;
                }
                if (tbAlarmModel.getOperator().equals("<")
                        && quotaDTO.getValue() < tbAlarmModel.getThreshold()) {
                    alarmModel = tbAlarmModel;
                    break;
                }
                if (tbAlarmModel.getOperator().equals("=")
                        && quotaDTO.getValue().equals(tbAlarmModel.getThreshold())) {
                    alarmModel = tbAlarmModel;
                    break;
                }
            }


        }

        return alarmModel;
    }


}
